<template>
  <a-row id="globalHeader" align="center" :wrap="false">
    <a-col flex="auto">
      <a-menu
        mode="horizontal"
        :selected-keys="selectedKeys"
        @menu-item-click="doMenuClick"
      >
        <a-menu-item
          key="0"
          :style="{ padding: 0, marginRight: '38px' }"
          disabled
        >
          <div class="logo">
            <img class="logo-img" src="@/assets/logo.jpeg" alt="" />
            <div class="title">狐答答</div>
          </div>
        </a-menu-item>
        <a-menu-item
          v-for="item in visibleRoutes"
          :key="item.path"
          class="menuItem"
          >{{ item.name }}
        </a-menu-item>
      </a-menu>
    </a-col>
    <a-col flex="100px">
      <div v-if="loginUserStore.loginUser.id">
        <a-dropdown trigger="hover">
          <a-avatar
            v-if="loginUserStore.loginUser.userAvatar"
            :imageUrl="loginUserStore.loginUser.userAvatar"
          >
          </a-avatar>
          <a-avatar v-else>{{ loginUserStore.loginUser.userName }}</a-avatar>
          <template #content>
            <a-doption @click="doLogout">登出</a-doption>
          </template>
        </a-dropdown>
      </div>
      <div v-else>
        <a-button type="primary" href="/user/login">登录</a-button>
      </div>
    </a-col>
  </a-row>
</template>
<script setup lang="ts">
import { routes } from "@/router/routes";
import { useRouter } from "vue-router";
import { computed, ref } from "vue";
import { useLoginUserStore } from "@/store/UserStore";
import checkAccess from "@/access/checkAccess";
import { userLogoutUsingPost } from "@/api/userController";
import message from "@arco-design/web-vue/es/message";

// 展示在菜单的路由数组
const visibleRoutes = computed(() => {
  return routes.filter((item) => {
    if (item.meta?.hideInMenu) {
      return false;
    }
    //判断当前用户是否有权限访问该菜单
    if (!checkAccess(loginUserStore.loginUser, item?.meta?.access as string)) {
      return false;
    }
    return true;
  });
});
const router = useRouter();
//点击跳转
const doMenuClick = (key: string) => {
  router.push({
    path: key,
  });
};

// Tab 栏选中菜单项
const selectedKeys = ref(["/"]);
// 路由跳转后，更新选中的菜单项
router.afterEach((to) => {
  selectedKeys.value = [to.path];
});

/*
 * 登出
 * */
const doLogout = async () => {
  const res = await userLogoutUsingPost();
  if (res.data.code == 0) {
    router.push({
      path: "/user/login",
      replace: true,
    });
  } else {
    message.error("退出登录失败， " + res.data.message);
  }
};

const loginUserStore = useLoginUserStore();
</script>
<style scoped>
.logo {
  display: flex;
  align-items: center;
}

.logo-img {
  width: 48px;
  height: 48px;
}

.title {
  margin-left: 14px;
  color: black;
}
</style>
